<?php


namespace App\Http\Controllers\Api\V1;


use App\Models\SmsCode;
use App\Models\User;
use App\Models\VerifyCode;
use App\Rules\VerifyCodeRule;
use App\Support\AliyunSms;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class ResetController extends BaseController
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    /*    public function __construct()
        {
            $this->middleware('guest:api');
        }*/

    /**
     * 密码更改
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function password(Request $request)
    {
        $this->validate($request, [
            'phone' => ['required', 'max:11', 'min:11', Rule::exists('users', 'phone')],
            'password' => 'required|string|min:6|confirmed',
            'password_confirmation' => 'required|string|min:6',
            'code' => 'required'
        ], [], [
            'code' => '验证码'
        ]);
        $data = $request->only(['phone', 'password', 'code']);
        // 验证短信验证码
        if (!SmsCode::verify($data['phone'], $data['code'], SmsCode::TYPE_FORGET_PASSWORD)) {
            return $this->json([], __('SMS Verification Code incorrect or expired'), config('apicode.verifyCodeFail.code'));
        }

        $user2 = User::where('phone', $data['phone'])->first();
        if (!$user2) {
            return $this->json([], config('apicode.noRecord.msg'), config('apicode.noRecord.code'));
        }

        $user2->password = bcrypt($data['password']);
        if ($user2->save()) {
            return $this->json([], '密码修改成功');
        }

        return $this->json([], config('apicode.serverError.msg'), config('apicode.serverError.code'));
    }

    /**
     * 发送验证码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function sendsms(Request $request)
    {
        $this->validate($request, [
            'phone' => ['required', 'max:11', 'min:11', Rule::exists('users', 'phone')],
        ]);

        $mobile = $request->input('phone');

        $code = geneSmsCode();
        $aliyunSms = new AliyunSms();

        if (!$aliyunSms->send($mobile, $code)) {
            return $this->json([], config('apicode.verifyCodeSendFail.msg'), config('apicode.verifyCodeSendFail.code'));
        }

        if (!SmsCode::send($mobile, $code, SmsCode::TYPE_FORGET_PASSWORD)) {
            return $this->json([], config('apicode.serverError.msg'), config('apicode.serverError.code'));
        }

        return $this->json();
    }
}